﻿/// <reference path="/Js/jsUtil.js"/> 
/// <reference path="/Js/main.js"/> 
/// <reference path="/Js/ext-5.0.0-gpl/build/ext-all.js"/> 
/// <reference path="/Js/app.js"/> 
/**
* 添加出售房源
*/
Ext.require('Region.Js.Region_Module');
Ext.require('RBAC.Js.RBAC_Module');
Ext.define("House.Js.Sells_Add", {
    show: function (SellId) {
        var winDom;
        var _title;
        if (SellId) _title = '修改'; else _title = '新增';
        var IsAllowMemChangeHouseInfo = RBAC.Js.RBAC_Module.SystemGetBool("House", "IsAllowMemChangeHouseInfo");
        var win = Ext.create('Ext.window.Window', {
            title: _title + '出售房源', height: 535, width: 900, modal: true,
            loader: {
                url: '/House/Templates/Sells_Add.htm', autoLoad: true, scripts: true,
                listeners: {
                    load: function (obj, eOpts) {
                        winDom = $("#" + obj.target.id);
                        $("input[name=SellId]", winDom).val(SellId);
                        renderUserControls(winDom);

                        function setSpinnerValue(control, $parent, val) {
                            $("input[name=" + control + "]", winDom).val(val);
                        }

                        $("input[name=SellBuildingId]", winDom).change(function () {
                            var val = $(this).val();
                            var _dong = "";
                            var _fang = "";
                            if ($("input[name=Dong]", winDom).val()) {
                                _dong = $("input[name=Dong]", winDom).val();
                            }
                            if ($("input[name=Fang]", winDom).val()) {
                                _fang = $("input[name=Fang]", winDom).val();
                            }
                            if (val.chkType("number"))
                                renderSimilar({ Dong: _dong, Fang: _fang, SellBuildingId: val }, $("table[name=dgBuilding]", winDom));
                            else
                                renderSimilar({ Dong: _dong, Fang: _fang, BuildingName: val }, $("table[name=dgBuilding]", winDom));
                            if (($("select[name=SellRegionArea]", winDom).val() == "0") || ($("select[name=SellRegionArea]", winDom).val() == "")) {
                                $("select[name=SellRegionArea]", winDom).val($(this).attr("data-area"));
                            }
                        });
                        $("input[name=CustomerTel]", winDom).change(function () {
                            renderSimilar({ CustomerTel: $(this).val() }, $("table[name=dgMobile]", winDom));
                            //中介判断
                            var agent = getRemoteObject("/Tools/Services/Tools_AgentMobiles.asmx/QueryTel", { tel: "'" + $(this).val() + "'" });
                            $(this).parent().find('.agent').remove();
                            if (agent) {
                                $(this).after("<span class='agent' style='color:red'>中介号码！</span>");
                            }

                        });
                        //备注变了就自动判断一下
                        if (IsAllowMemChangeHouseInfo) {
                            $("input[name=Mem]", winDom).change(function () {
                                inteligentFillBlank($(this).val());
                            });
                        }
                        $("input[name=UnitPrice]", winDom).change(function () {
                            calcTotalPrice();
                        });
                        $("input[name=TotalPrice]", winDom).change(function () {
                            calcUnitPrice();
                        });
                        $("input[name=HouseArea]", winDom).change(function () {
                            calcTotalPrice();
                        });
                        $("input[name=Fang]", winDom).change(function () {
                            if (!$("input[name=HouseFloor]", winDom).val()) {
                                var _fang = $("input[name=Fang]", winDom).val();
                                if (_fang.length == 4)
                                    $("input[name=HouseFloor]", winDom).val(_fang.substring(0, 2));
                                else if (_fang.length == 3)
                                    $("input[name=HouseFloor]", winDom).val(_fang.substring(0, 1));
                            }
                            loadRenderSimilar();
                        });
                        $("input[name=Dong]", winDom).change(function () {
                            loadRenderSimilar();
                        });
                        $("select[name=SellFace]", winDom).change(function () {
                            var face = $(this).val();
                            if ([5, 6, 8, 10].indexOf(face) > -1) {
                                $("input[name=Ting],input[name=Chu],input[name=Wei]").prop("readonly", true).val(0);
                            } else
                                $("input[name=Ting],input[name=Chu],input[name=Wei]").prop("readonly", false);
                            if (face == 5) {
                                $("input[name=Shi]").prop("readonly", true).val(0);
                            } else
                                $("input[name=Shi]").prop("readonly", false);
                        });
                        init();
                        //预设
                        function init() {
                            $("select[name=SellFace]", winDom).val(2);
                            $("select[name=Decoration]", winDom).val(1);
                        }

                        //产证年份下拉框，9.2版的node-webkit不管用
                        $(".xclass-property-year").each(function () {
                            var _select = $(this);
                            var _selectval = _select.attr("value");
                            var currentYear = new Date().getFullYear();
                            _select.empty();
                            _select.addOption("未知");
                            for (var i = 0; i <= 15; i++) {
                                _select.addOption(currentYear - i + "年");
                            }
                            _select.addOption(2000 + "年以前");

                        });
                        function loadRenderSimilar() {
                            var _dong = "";
                            var _fang = "";
                            if ($("input[name=Dong]", winDom).val()) {
                                _dong = $("input[name=Dong]", winDom).val();
                            }
                            if ($("input[name=Fang]", winDom).val()) {
                                _fang = $("input[name=Fang]", winDom).val();
                            }
                            if ($("input[name=SellBuildingId]", winDom).val().chkType("number"))
                                renderSimilar({ Dong: _dong, Fang: _fang, SellBuildingId: $("input[name=SellBuildingId]", winDom).val() }, $("table[name=dgBuilding]"));
                            else
                                renderSimilar({ Dong: _dong, Fang: _fang, SellBuildingId: $("input[name=SellBuildingId]", winDom).val() }, $("table[name=dgBuilding]"));
                        }
                        function renderSimilar(param, $dg) {
                            var _type;
                            if ($dg.attr("name") == 'dgMobile')
                                _type = 'mobile';
                            else
                                _type = 'building';
                            $dg.datagrid({
                                url: "House/Services/House_Sells.asmx/GetLists",
                                method: 'GET',
                                data: $.extend({}, param),
                                idFiled: 'SellId',
                                loadMsg: '正在加载，请稍候……',
                                pagination: false,
                                rownumbers: false,
                                pageNumber: 1, headers: { 'Content-Type': 'application/json;utf-8' },
                                pageSize: 10,
                                //toolbar: $("div[name=toolbar]", "#House-Sell_All"),
                                pagination: false, width: 525,
                                singleSelect: true, height: 200,
                                columns: [[
                                    { field: 'BuildingName', title: '小区', width: 100, align: 'left', hidden: _type == 'building' ? true : false },
                                    { field: 'Dong', title: '栋房', width: 50, align: 'center', formatter: function (v, r, k) { return v + "#" + r.Fang; } },
                                    { field: 'HouseFloor', title: '楼层', width: 50, align: 'center', formatter: function (v, r, k) { return v + "/" + r.HouseTotalFloor; } },
                                    { field: 'Shi', title: '户型', width: 40, align: 'center', formatter: function (v, r, k) { return v + "-" + r.Ting; } },
                                    { field: 'HouseArea', title: '面积', width: 60, align: 'center', formatter: function (v, r, k) { return v + "平"; } },
                                    { field: 'UnitPrice', title: '价格', width: 60, align: 'left', formatter: function (v, r, k) { return v + "元/平"; } },
                                    { field: 'Decoration', title: '装修', width: 40, align: 'center', formatter: function (v, r, k) { return X_DECORATEKEYS[v]; } },
                                    { field: 'LastTime', title: '时间', width: 100, formatter: formatDate, align: 'center' },
                                    { field: 'State', title: '状态', width: 40, align: 'center', formatter: function (v, r, k) { return X_SELLSTATE[r.State]; } }
                                ]],
                                loadFilter: function (data) {
                                    return loadFilter(data);
                                },
                                onLoadSuccess: function (data) {
                                    var msg;
                                    if (data.rows.length) {
                                        msg = '加载 ' + data.rows.length + ' 条记录成功!';
                                    }
                                    else {
                                        msg = '没有数据!';
                                    }
                                    $.messager.show({ title: '操作提示', msg: msg });
                                },
                                onClickRow: function (rowIndex, rowData) {
                                    popMenu('/House/Js/Sells_View', rowData.SellId);
                                }
                            });
                        }
                        function inteligentFillBlank(txt) {
                            var sellObj = parseHouseSell(txt);
                            if (sellObj.Building) {
                                ///尝试从服务端取id
                                $.get("Region/Services/Region_Buildings.asmx/QueryName", { BuildName: sellObj.Building }, function (t) {
                                    //$("input[name=SellBuildingId]",winDom).combobox('setValues', sellObj.Building);
                                    setComboboxValue('SellBuildingId', 'House-Sell_Add', sellObj.Building, $(t).find("BuildingId").text());
                                });
                            }
                            if (sellObj.Dong) {
                                $("input[name=Dong]", winDom).val(sellObj.Dong);
                            }
                            if (sellObj.Fang) {
                                $("input[name=Fang]", winDom).val(sellObj.Fang);
                            }
                            if (sellObj.HouseFace) {
                                $("select[name=SellFace]", winDom).setSelectedText(sellObj.HouseFace);
                            }
                            if (sellObj.Contact) {
                                $("input[name=CustomerName]", winDom).val(sellObj.Contact);
                            }
                            if (sellObj.Tel) {
                                $("input[name=CustomerTel]", winDom).val(sellObj.Tel);
                            }
                            if (sellObj.Area) {
                                $("input[name=HouseArea]", winDom).val(sellObj.Area);
                            }
                            if (sellObj.UnitPrice) {
                                if (!$("input[name=UnitPrice]", winDom).val())
                                    $("input[name=UnitPrice]", winDom).val(sellObj.UnitPrice);
                            }
                            if (sellObj.TotalPrice) {
                                $("input[name=TotalPrice]", winDom).val(sellObj.TotalPrice);
                            }
                            if (sellObj.Decoration) {
                                $("select[name=Decoration]", winDom).setSelectedText(sellObj.Decoration);
                            }
                            if (sellObj.RegionArea) {
                                $("select[name=SellRegionArea]", winDom).setSelectedText(sellObj.RegionArea);
                            }
                            if (sellObj.Shi) {
                                setSpinnerValue("Shi", "House-Sell_Add", sellObj.Shi);
                            }
                            if (sellObj.Ting) {
                                setSpinnerValue("Ting", "House-Sell_Add", sellObj.Ting);
                            }
                            if (sellObj.Chu) {
                                setSpinnerValue("Chu", "House-Sell_Add", sellObj.Chu);
                            }
                            if (sellObj.Wei) {
                                setSpinnerValue("Wei", "House-Sell_Add", sellObj.Wei);
                            }
                            if (sellObj.Floor) {
                                setSpinnerValue("HouseFloor", "House-Sell_Add", sellObj.Floor);
                            }
                            if (sellObj.TotalFloor) {
                                setSpinnerValue("HouseTotalFloor", "House-Sell_Add", sellObj.TotalFloor);
                            }
                            
                        }

                        function parseHouseSell(txt) {
                            var houseObj = {};
                            //117417	117417		陈先生 13909696373 [查询中] 百度陈先生 [查询中]	毛坯 证未满5年	翡翠路与紫篷路交叉口	经开区	2005 年	3室2厅1卫	5 / 6	75 万元	毛坯	多层	：4237.28813559322 元	177 平方	学林雅苑 5-501面积：177 平方  单价：4237.28813559322 元 楼型：多层  装潢：毛坯  总价：75 万元 楼层：5 / 6  户型：3室2厅1卫  建于：2005 年  区域：经开区  地址：翡翠路与紫篷路交叉口  其它：毛坯 证未满5年  房主：陈先生 13909696373 [查询中] 百度陈先生 [查询中] 百度点此查看电话号码业务员： 收藏地图添加跟进暂无跟进,请添加跟进	2010/10/12 15:39:00	中介宝 技术中心 总管理员	出售
                            ///取电话
                            var pattern = /[0-9]{7,20}/gi;
                            var arr;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                if (arr.length > 0) {
                                    houseObj.Tel = arr[0];
                                }
                            }
                            ///取总价
                            pattern = /([0-9]*(.[0-9])?)\s*万/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.TotalPrice = arr[0].replace("万", "");
                            }
                            ///取单价
                            pattern = /\b([0-9]{4,5}(.[0-9]*)?)\b\s*元?/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.UnitPrice = arr[0].replace("元", "").trim();
                            }
                            //单价优先取带元的
                            pattern = /\b([0-9]{4,5}(.[0-9]*)?)\s*元/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.UnitPrice = arr[0].replace("元", "").trim();
                            }

                            //取几室几厅
                            pattern = /[\d]\s*([\/-]\s*\d)+/gi;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                for (var i = 0; i < arr.length; i++) {
                                    var arr1 = arr[i].match(/\d/gi);
                                    if ((arr1[0] == "2" && arr1[1] == "2") || arr1[0] <= arr1[1]) {
                                        //区分层
                                        houseObj.Floor = arr1[0];
                                        houseObj.TotalFloor = arr1[1];
                                    }
                                    else {
                                        houseObj.Shi = arr1[0];
                                        houseObj.Ting = arr1[1];

                                        if (arr1.length > 2)
                                            houseObj.Chu = arr1[2];
                                        if (arr1.length > 3)
                                            houseObj.Wei = arr1[3];
                                    }
                                }
                            }

                            //优先处理层的方式
                            pattern = /\s*(\d*)\s*\/\s*(\d*)\s*/;
                            if (pattern.test(txt)) {
                                if (pattern.test(txt)) {
                                    arr = txt.match(pattern);
                                    if (arr.length > 2) {
                                        houseObj.Floor = arr[1];
                                        houseObj.TotalFloor = arr[2];
                                    }
                                }
                            }
                            //如果有几室几厅几卫，那要优先处理
                            pattern = /(\d*)室/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.Shi = arr[1];
                            }
                            //如果有几室几厅几卫，那要优先处理
                            pattern = /(\d*)厅/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.Ting = arr[1];
                            }
                            //如果有几室几厅几卫，那要优先处理
                            pattern = /(\d*)厨/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.Chu = arr[1];
                            }
                            //如果有几室几厅几卫，那要优先处理
                            pattern = /(\d*)卫/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.Wei = arr[1];
                            }
                            //取小区
                            pattern = /[\u4e00-\u9fa5·]{3,20}/g;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                var _skipStrs = ['女士', '先生', '姐', '询', '证', '与'];
                                for (var _i = 0; _i < arr.length; _i++) {
                                    var _isSkip = false;
                                    for (var _a = 0; _a < _skipStrs.length; _a++) {
                                        if (arr[_i].indexOf(_skipStrs[_a]) > -1) {
                                            _isSkip = true;
                                            break;
                                        }
                                    }
                                    if (!_isSkip) {
                                        //过滤区域
                                        for (var _a in X_AREA) {
                                            if (_a.indexOf("_") < 0) continue;
                                            if (arr[_i].indexOf(X_AREA[_a].AreaName) > -1) {
                                                _isSkip = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (_isSkip) continue;
                                    houseObj.Building = arr[_i].replace('·', '');
                                    break;
                                }

                            }

                            //联系人
                            pattern = /[\u4e00-\u9fa5·][女士|先生][\u4e00-\u9fa5·]/;
                            var pattern1 = /[\u4e00-\u9fa5·][\u4e00-\u9fa5·][姐]/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                houseObj.Contact = arr[0];
                            }
                            else if (pattern1.test(txt)) {
                                arr = txt.match(pattern1);
                                houseObj.Contact = arr[0];
                            }
                            //栋号房号
                            pattern = /[\d\w]+[ ]?[#|栋|-][\d]{2,5}/ig;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                arr = arr[0].match(/[\d\w]+/ig);
                                houseObj.Dong = arr[0];
                                houseObj.Fang = arr[1];
                            }

                            ///取面积
                            pattern = /[^\d#栋]([\d]{2,3})[m|平]/;
                            if (pattern.test(txt)) {
                                arr = txt.match(pattern);
                                var acre = arr[0].replace("m", "").replace("平", "").replace(" ", "");
                                if (acre > 20 && acre < 200) {
                                    if ($("input[name=Shi]", winDom).val() == "") {
                                        if (acre <= 90) {
                                            houseObj.Shi = "2"
                                            houseObj.Ting = "1";
                                            houseObj.Chu = "1";
                                            houseObj.Wei = "1";
                                        }
                                        else if (acre > 90 && acre < 130) {
                                            houseObj.Shi = "3"
                                            houseObj.Ting = "2";
                                            houseObj.Chu = "1";
                                            houseObj.Wei = "1";
                                        }
                                        else {
                                            houseObj.Shi = "4"
                                            houseObj.Ting = "2";
                                            houseObj.Chu = "1";
                                            houseObj.Wei = "1";
                                        }
                                    }
                                    houseObj.Area = acre;
                                }
                            }
                            //没取到面积的话
                            if (!houseObj.Area) {
                                pattern = /(\d*)\s*平/;
                                arr = txt.match(pattern);
                                if (pattern.test(txt)) {
                                    houseObj.Area = arr[1];
                                }
                            }
                            ///装修方式
                            if (txt.indexOf("毛坯") > -1) { houseObj.Decoration = "毛坯"; }
                            if (txt.indexOf("中装") > -1 || txt.indexOf("中等装修") > -1 || txt.indexOf("普装") > -1 || txt.indexOf("普通装修") > -1) { houseObj.Decoration = "中装"; }
                            if (txt.indexOf("豪装") > -1 || txt.indexOf("精装") > -1) { houseObj.Decoration = "豪装"; }
                            if (txt.indexOf("简装") > -1) { houseObj.Decoration = "简装"; }
                            ///区域
                            for (var _j in X_AREA) {
                                if (_j.indexOf("_") < 0) continue;
                                if (txt.indexOf(X_AREA[_j].AreaName) > -1) {
                                    houseObj.RegionArea = X_AREA[_j].AreaName;
                                    break;
                                }
                            }
                            ///房屋类型
                            for (var _j = 0; _j < X_HOUSEFACE.length; _j++) {
                                if (txt.indexOf(X_HOUSEFACE[_j]) > -1) {
                                    houseObj.HouseFace = X_HOUSEFACE[_j];
                                }
                            }

                            return houseObj;
                        }
                        function calcTotalPrice() {
                            var _HouseArea = $("input[name=HouseArea]", winDom).val();
                            var _UnitPrice = $("input[name=UnitPrice]", winDom).val();
                            if (_HouseArea.chkType("number") && _UnitPrice.chkType("number")) {
                                $("input[name=TotalPrice]", winDom).val(_HouseArea * _UnitPrice / 10000);
                            }
                        }
                        function calcUnitPrice() {
                            var _HouseArea = $("input[name=HouseArea]", winDom).val();
                            var _TotalPrice = $("input[name=TotalPrice]", winDom).val();
                            if (_HouseArea.chkType("number") && _TotalPrice.chkType("number")) {
                                $("input[name=UnitPrice]", winDom).val(_TotalPrice * 10000 / _HouseArea);
                            }
                        }
                    }
                }
            },
            buttons: [
            {
                text: "确认",
                handler: function () {
                    var _win = this.up('window');
                    //有效性验证
                    if (!$("form[name=fmAdd]", winDom).form("validate")) {
                        return;
                    }

                    //小区有效性验证
                    var _buildingId = $('input[name=SellBuildingId]', winDom).val();
                    if (!_buildingId.chkType("int")) {
                        //从服务器获取小区id
                        var obj = getRemoteObject("Region/Services/Region_Buildings.asmx/QueryName", { BuildName: "'" + _buildingId + "'" });
                        if (!obj) {
                            $.messager.show({ title: '操作提示', msg: "小区不正确。" });
                            return false;
                        }
                        else {
                            $('input[name=SellBuildingId]', winDom).val(_buildingId);
                        }
                    }
                    $.post("/House/Services/House_Sells.asmx/Add", $("form[name=fmAdd]", winDom).serializeArray(), function (data) {
                        switch ($(data).find("ServiceStateKeys").text()) {
                            case "Success":
                                $.messager.show({ title: "操作提示", msg: "操作成功" });
                                _win.close();
                                RBAC.Js.RBAC_Module.render('House.Js.Sells_List');
                                break;
                            default:
                                Ext.Msg.show({ title: "操作提示", message: "保存操作失败" });
                                break;
                        }
                    });
                }
            }, {
                text: "关闭",
                handler: function () {
                    this.up("window").close();
                }
            }],
            listeners: {
                close: function () {
                }
            }
        }).show();

    },
    constructor: function (config) {
        this.initConfig(config);
    }
});
